import React, { useEffect, useState } from 'react';
import { ProCard, ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, Table, Input, Tag, message, Space } from 'antd';
import type { Key } from 'antd/lib/table/interface';
import 'antd/dist/antd.css';
import { connect, useDispatch } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { createBrowserHistory } from 'history';

const history = createBrowserHistory();
export type TableListItem = {
  key: number;
  stuName: string;
  stuCode: string;
  majorLabel: string;
  classLabel: string;
  phoneNumber: string;
};

const columns: ProColumns<TableListItem>[] = [
  {
    title: <b>姓名</b>,
    width: 200,
    align: 'left',
    dataIndex: 'stuName',
  },
  {
    title: <b>学号</b>,
    width: 200,
    align: 'left',
    dataIndex: 'stuCode',
  },
  {
    title: <b>专业</b>,
    width: 200,
    align: 'left',
    dataIndex: 'majorLabel',
  },
  {
    title: <b>班级</b>,
    width: 200,
    dataIndex: 'classLabel',
  },
  {
    title: <b>电话</b>,
    width: 200,
    dataIndex: 'phoneNumber',
  },
];

function ClusterByOne() {
  // 存储用户选择的行的keys
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
  // 存储选中学生对象的数组
  const [selectedStudents, setSelectedStudents] = useState<TableListItem[]>([]);
  // 存储input框中分群标题
  const [clusterName, setClusterName] = useState<string>('');
  // 存储学生列表
  const [tableListData, setTableListData] = useState<TableListItem[]>([]);
  const dispatch = useDispatch();
  // 点击关闭按钮触发删除学生姓名的操作
  const handleRemoveStudent = (student: any) => {
    const updatedSelectedStudents = selectedStudents.filter(
      (selectedStudent) => selectedStudent.key !== student.key,
    );
    setSelectedStudents(updatedSelectedStudents);
  };

  // 点击添加至分群
  const handleAddToCluster = () => {
    const selectedStudentsData = tableListData.filter((item) => selectedRowKeys.includes(item.key));
    setSelectedStudents(selectedStudentsData);
  };

  //点击创建分群
  const handleCreateCluster = () => {
    //假如没有选择学生
    if (selectedStudents.length === 0) {
      message.warn('请先选择学生再创建分群！');
      return;
    }
    // 构建要发送给后端的数据结构
    const postData = {
      campClusterInfo: {
        clusterLabel: clusterName,
        createBy: '2022073', // 这里可以是当前登录用户的ID或其他标识
      },
      campClusterUserList: selectedStudents.map((student) => ({
        userAccount: student.stuCode,
      })),
    };
    // console.log(postData);
    dispatch({
      type: 'Model_createclusterModel/getcreateClusterEffects',
      payload: {
        data: postData,
        callback: (response: any) => {
          // 这里可以处理后端返回的响应数据
          // console.log(response);
          if (response.code === '200') {
            message.success('创建成功！');
          } else {
            message.error('创建失败了，请重新创建！');
          }
          window.location.reload();
        },
      },
    });
  };

  useEffect(() => {
    //获取数据接口
    dispatch({
      type: 'Model_createclusterModel/getstudentListEffects',
      payload: {
        // code: JSON.parse(props.user.currrentuser).account,
        code: 2022073,
        callback: (value: any) => {
          // console.log(value);
          setTableListData(value);
        },
      },
    });
  }, []);
  return (
    <PageContainer>
      <div>
        <ProCard split="horizontal">
          {/* 左侧卡片 */}
          <ProCard title="创建分群" colSpan="80%">
            <ProCard split='vertical'>
              <ProCard title="分群名称" colSpan="30%">
                <Input value={clusterName} onChange={(e) => setClusterName(e.target.value)} />
              </ProCard>
              <ProCard title="已添加的学生">
                {selectedStudents.map((student) => (
                  <Tag
                    key={student.key}
                    closable
                    onClose={() => handleRemoveStudent(student)}
                    style={{ marginBottom: '8px' }}
                  >
                    {student.stuName}
                  </Tag>
                ))}
                <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '16px' }}>
                  <Space size="middle">
                    <Button type="primary" onClick={handleCreateCluster}>
                      创建分群
                    </Button>
                    <Button type="primary" onClick={() => { history.push("./list"), window.location.reload() }}>返回分群列表</Button>
                  </Space>
                </div>
              </ProCard>
            </ProCard>
          </ProCard>
          {/* 右侧卡片 */}
          <ProCard title="个体分群">
            <ProTable<TableListItem>
              columns={columns}
              //配置表格的行选择功能。
              rowSelection={{
                selectedRowKeys, // 设置用户选择的行
                onChange: (keys) => setSelectedRowKeys(keys), // 更新用户选择的行
                selections: [
                  Table.SELECTION_ALL, //全选
                  Table.SELECTION_INVERT, //反选
                  Table.SELECTION_NONE, //全不选
                ],
              }}
              dataSource={tableListData}
              options={false}
              search={false}
              pagination={{ pageSize: 10 }}
              rowKey="key"
              headerTitle="学生列表"
              toolBarRender={() => [
                <Button key="show" type="primary" onClick={handleAddToCluster}>
                  添加至分群
                </Button>,
              ]}
            />
          </ProCard>
        </ProCard>
      </div>
    </PageContainer>
  );
}

export default connect(({ Model_createclusterModel }: any) => ({
  Model_createclusterModel,
}))(ClusterByOne);
